<!-- 订单详情页 -->
<template>
    <div class="order-detail">
        <van-nav-bar title="订单详情" left-arrow @click-left="goBack" />

        <!-- 订单状态 -->
        <div class="order-status">
            <van-tag :color="statusColor">{{ statusText }}</van-tag>
        </div>

        <!-- 订单信息 -->
        <van-cell-group title="订单信息">
            <van-cell title="订单编号" :value="orderInfo.orderNumber" class="order-number"/>
            <van-cell title="创建时间" :value="formatTime(orderInfo.createTime)" />
            <van-cell title="支付方式" :value="orderInfo.paymentChannelText" />
            <van-cell title="实付金额" :value="`￥${orderInfo.actualAmount}`" value-class="price" />
        </van-cell-group>

        <!-- 商品列表 -->
        <van-cell-group title="商品信息">
            <van-card v-for="item in orderInfo.items" :key="item.id" :price="`${item.price}`" :title="item.name"
                :desc="`数量: ${item.quantity}`" :thumb="item.imgUrl" />
        </van-cell-group>

        <!-- 操作按钮（根据状态显示） -->
        <div class="actions" v-if="orderInfo.status === 'OrderStatus.PENDING'">
            <van-button plain type="danger" @click="cancelOrder">取消订单</van-button>
            <van-button type="primary" @click="goToPayment">去支付</van-button>
        </div>
        <div class="actions" v-else-if="orderInfo.status === 'OrderStatus.CANCELLED'">
            <van-button type="primary" @click="reOrder">重新下单</van-button>
        </div>
    </div>

    <!-- 二维码模态框 -->
    <van-dialog v-model:show="showCode" :showConfirmButton="false" :title="null" class="payment-dialog">
        <!-- 自定义标题栏：返回按钮 + 标题 -->
        <div class="dialog-header">
            <van-icon name="cross" class="close-btn" @click="closeCode" />
            <h3 class="dialog-title">微信支付</h3>
        </div>

        <div class="dialog-content">
            <div>订单编号：{{ orderInfo.orderNumber }}</div>
            <img :src="codeImg" class="qrcode-img" alt="二维码支付" />
        </div>
    </van-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import api from '@/api/history.js'
import { useOrderStore, useProductStore } from '@/store/counter'
import { OrderStatus, PaymentChannel } from '@/enums'
import Qrcode from 'qrcode'

// 路由与状态
const router = useRouter()
const route = useRoute()
const showCode = ref(false)
const codeImg = ref('')
// 支付状态轮询计时器
const pollTimer = ref(null);
const orderId = ref(route.params.orderId)
console.log("order:", orderId.value)
// const orderId = ref(29)
const orderInfo = ref({
    orderNumber: 'ORDER7357949004811997184',
    createTime: '2025-08-04 09:43:32.455141',
    status: 'OrderStatus.PENDING',
    paymentChannel: 'wechat',
    paymentChannelText: '微信支付',
    actualAmount: '0.01',
    items: [
        {
            id: 22,
            name: '测试商品',
            price: '0.01',
            quantity: 1,
            imgUrl: 'http://sz4rr0buo.hn-bkt.clouddn.com/%E8%8A%92%E6%9E%9C%E5%A5%B6%E6%98%94.png'
        }
    ]
})




// 状态颜色计算（基于枚举判断）
const statusColor = ref(() => {
    switch (orderInfo.value.status) {
        case OrderStatus.PENDING: return "#faad14";
        case OrderStatus.PAID: return "#07c160";
        case OrderStatus.CANCELLED: return "#86909c";
        default: return "#666";
    }
})

// 格式化时间
const formatTime = (time) => time ? new Date(time).toLocaleString() : ''

// 初始化：加载订单详情
// onMounted(async () => {
//     try {
//         // const res = await api.get(`/order/detail/${orderId.value}`)
//         // console.log('获取订单详情',res)
//         // orderInfo.value = {
//         //     ...res.data,
//         //     // 转换支付渠道为中文
//         //     paymentChannelText: {
//         //         [PaymentChannel.ALIPAY]: '支付宝支付',
//         //         [PaymentChannel.WECHAT]: '微信支付',
//         //         [PaymentChannel.UNIONPAY]: '银联支付',
//         //         [PaymentChannel.BALANCE]: '余额支付'
//         //     }[res.data.paymentChannel] || '未知渠道'
//     } catch (err) {
//     showToast('获取订单失败')
// } 
// })

// 返回上一页
const goBack = () => router.back()

// 获取支付链接
const getPaymentUrl = async (paymentId) => {
    const res = await api.post(`/payment/pay/${paymentId}`)
    console.log('调用通用支付接口获取的数据:', res);
    return res.data.data

}


const orderStore = useOrderStore()
const productStore = useProductStore()
console.log('商品ID：',orderInfo.value.items[0]["id"])
productStore.setProductInfo(orderInfo.value.items[0]["id"])

// 去支付：创建支付记录并跳转支付页
const goToPayment = async () => {
    try {
        // 调用后端创建支付记录接口
        const res = await api.post(`/payment/create/${orderId.value}`)
        console.log('创建支付记录', res)
        const paymentId = res.data.data.payment_id
        console.log('支付记录ID', paymentId)

        // 获取支付链接
        const payment_data = await getPaymentUrl(paymentId)
        console.log('支付数据>>>>>>!!!!!!!!', payment_data)
        // 设置订单信息到pinia
        orderStore.setOrderInfo(orderId.value, orderInfo.value.actualAmount, orderInfo.value.paymentChannel)
        console.log('pinia中的数据》》。》》:', orderStore.orderId)

        // 余额支付直接调用支付接口（无二维码页）
        if (orderInfo.value.paymentChannel == "balance") {
            result = await api.post(`/payment/balance/${paymentId}`)
            console.log("支付完成：", result)
            router.push(`/payment/sandbox_result?out_trade_no=${orderInfo.value.orderNumber}`)
        } else if (orderInfo.value.paymentChannel == "alipay") {
            // 支付宝支付直接跳转至支付宝支付链接
            const payment_url = payment_data['payment_url']
            console.log('payment_url~~~~~~~~~~~~~~~~~~~~~~~~', payment_url)
            if (payment_url) {
                console.log('即将跳转的支付链接:', payment_url); // 再次确认链接
                window.location.href = payment_url;
            } else {
                console.error('支付链接为空，无法跳转');
                showToast('支付链接获取失败，请重试');
            }
        } else if (orderInfo.value.paymentChannel == "wechat") {
            const code_url = payment_data['code_url']
            console.log('code_url', code_url)
            // 生成二维码并显示弹窗
            Qrcode.toDataURL(code_url).then((url) => {
                showCode.value = true//显示弹窗
                codeImg.value = url//显示二维码图片
                // 启动轮询（每3秒查一次支付状态）
                startPolling(orderInfo.value.orderNumber); // 传入订单编号用于查询
            })
        }
    } catch (err) {
        showToast(err.response?.data?.data?.message || '支付准备失败')
    }
}



// 取消订单
const cancelOrder = async () => {
    showConfirmDialog({
        title: '取消订单',
        message: '确定取消订单吗？未支付订单取消后将释放库存'
    }).then(async () => {
        try {
            res = await api.post(`/payment/order/cancel/${orderId.value}`)
            console.log('取消订单', res)
            orderInfo.value.status = OrderStatus.CANCELLED // 本地更新状态
            showToast('订单已取消')
        } catch (err) {
            showToast('取消失败')
        }
    })
}

// 重新下单
const reOrder = () => {
    router.push('/cart')
}


// 启动轮询
const startPolling = (out_trade_no) => {
    // 清除已有计时器，避免重复
    if (pollTimer.value) clearInterval(pollTimer.value);
    // 每3秒查询一次
    pollTimer.value = setInterval(async () => {
        try {
            // 调用后端查询支付状态接口（需后端提供）
            const res = await api.post(`/payment/payment_status/${out_trade_no}`);
            const status = res.data.data.payment_status;
            console.log('微信支付的订单支付状态status>>>>>>>>>>>>:', status)
            if (status === 'paid') {
                // 支付成功：关闭弹窗、清除计时器、跳转结果页
                showCode.value = false;
                clearInterval(pollTimer.value);
                router.push(`/payment/sandbox_result?out_trade_no=${out_trade_no}`);
            } else if (status === 'timeout') {
                // 支付超时：提示并关闭弹窗
                showToast('支付已超时');
                showCode.value = false;
                clearInterval(pollTimer.value);
            } else if (status === 'failed') {
                // 支付失败：提示并关闭弹窗
                showToast('支付失败');
                showCode.value = false;
                clearInterval(pollTimer.value);
            }
        } catch (err) {
            console.error('轮询支付状态失败', err);
        }
    }, 3000);
};

// 关闭二维码弹窗时清除计时器
const closeCode = () => {
    showCode.value = false;
    if (pollTimer.value) {
        clearInterval(pollTimer.value);
        pollTimer.value = null;
    }
};




</script>

<style scoped>
.order-detail {
    padding: 16px;
    background: #f5f5f5;
    min-height: 100vh;
}

.order-status {
    background: #fff;
    padding: 16px;
    text-align: center;
    border-radius: 8px;
    margin-bottom: 10px;
}

.order-number{
    font-size: 12px;
}

.price {
    color: #ee0a24;
    font-weight: bold;
}

.actions {
    display: flex;
    gap: 10px;
    margin-top: 20px;
}

.actions .van-button {
    flex: 1;
}

/* 返回按钮 */
.close-btn {
    position: absolute;
    left: 10px;
    top: px;
    font-size: 20px;
    color: #666;
}

/* 内容区域 */
.dialog-content {
    padding: 20px 16px;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 去除默认内容区padding */
:deep(.payment-dialog .van-dialog__content) {
    padding: 0 !important;
}

/* 1. 模态框整体样式 */
:deep(.payment-dialog) {
    width: 90% !important;
    max-width: 350px;
}

/* 2. 内容区域：文字/二维码的父容器 */
:deep(.payment-dialog .van-dialog__content) {
    padding: 20px 16px !important;
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
}

/* 标题文字 */
.dialog-title {
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin: 0;
}

/* 自定义标题栏 */
.dialog-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 16px 16px 0;
    position: relative;
    width: 100%;
}

/* 3.订单编号文本 */
.dialog-content>div {
    margin-bottom: 16px;
    color: #333;
    font-size: 12px;
    word-break: break-all;
    max-width: 90%;
}


/* 4. 二维码图片 */
.qrcode-img {
    display: block;
    width: 200px;
    height: 200px;
    padding: 8px;
    background: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    margin: 0 auto;
    /* 居中显示 */
}

/* 5. 底部按钮区域 */
:deep(.payment-dialog .van-dialog__footer) {
    padding: 0 16px 16px !important;
}
</style>